<template>
  <el-table
      ref="ZTableRef"
      :data="tableData"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      class="upgradeTable"
      default-expand-all
      v-bind="$attrs"
      row-key="id"
      :highlight-current-row="highlight"
      @handleCurrentChange="handleCurrentChange"
      @selection-change="handleSelectionChange"
      @row-click="rowClick"
      :row-class-name="tableRowClassName"
      :row-style="tableRowStyle"
  >
    <el-table-column
        v-for="(column, index) in tableDataHeader"
        :key="index"
        :align="column.align"
        :fixed="column.fixed"
        :label="column.label"
        :prop="column.prop"
        :show-overflow-tooltip="column.tooltip"
        :sortable="column.sortable"
        :type="column.type"
        :width="column.width"
    >
      <template v-if="column.slotName" #default="scope">
        <!-- 这里通过scope.row传递当前行的数据 -->
        <slot :col="column" :scope :item="scope.row" :name="column.keyName"></slot>
      </template>

      <template v-if="column.children">
        <el-table-column
            v-for="(colChild, childIndex) in column.children"
            :key="childIndex"
            :align="colChild.align"
            :fixed="colChild.fixed"
            :label="colChild.label"
            :prop="colChild.prop"
            :show-overflow-tooltip="colChild.tooltip"
            :sortable="colChild.sortable"
            :type="colChild.type"
            :width="colChild.width"
        >
        </el-table-column>
      </template>

      <!-- <template #default="scope" v-if="column.slotName">
        <slot  :name="column.keyName" :column="scope"></slot>
    </template> -->

      <template v-if="column.operate" #default="scope">
        <span v-for="item in column.children">
          <el-button
              v-if="!item.isShow"
              v-show="
              item['btnHidden'] ? executeFun(item['btnHidden'], scope.row) : true
            "
              :disabled="item.disabled"
              :key="item.prop"
              :link="item.link"
              :plain="item.plain"
              :type="item.type"
              @click="btnClick(item.method, scope.row, scope.$index, item.methodType)"
          >{{ item.label }}
          </el-button>
        </span>
      </template>
    </el-table-column>
    <template #empty>
      <div class="empty-total">
        <div class="custom-empty">
          <i class="el-icon-warning"></i>
        </div>
        <div class="empty-text">
          <span>暂无数据</span>
        </div>
      </div>
    </template>
  </el-table>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed, watch} from 'vue';
import {TableDataItem, TableColumn} from '@/views/components/table/ZTable/type.ts';
import {useTableColumnsStore} from '@/store/modules/tableColumnsStore/tableColumnsStore.ts';
import {getLocalStorage} from '@/utils';
import {StorageEnum} from '@/enums/storageEnum';
import {ElMessage} from 'element-plus';

const {Z_USER_ID} = StorageEnum;

// 定义接收的 props
const props = defineProps({
  tableData: {
    type: Array<TableDataItem>,
    default: () => {
      return [];
    },
  },
  tableDataHeader: {
    type: Array<TableColumn>,
    default: () => {
      return [];
    },
  },
  tableId: {
    type: String,
    default: () => {
      return '';
    },
  },
  highlight: {
    type: Boolean,
    default: false
  },
  tableRowStyle: {
    type: Object,
    default: () => {
      return {
        height: '40px',
        minHeight: '40px',
      }
    }
  },
  showSettings: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  height: {
    type: Number,
    default: () => {
      return 0;
    },
  }
});

const executeFun = <T, R>(fun: (arg: T) => R, row: T): R => {
  return fun(row);
};

const tableRowClassName = ({
                             row,
                             rowIndex,
                           }) => {
  if (rowIndex % 2 === 0) {
    return 'warning-row'
  } else if (rowIndex % 2 === 1) {
    return 'success-row'
  }
  return 'upgradeRow'
}


// 定义可触发的事件
const emits = defineEmits<{
  (e: 'closeSetting'): void;
  (e: 'rowClick', row: TableDataItem, index?: number): void;
  (e: 'deleteRow', row: TableDataItem, index?: number): void;
  (e: 'editRow', row: TableDataItem, index?: number, methodType?: string): void;
  (e: 'detailRow', row: TableDataItem, index?: number): void;
  (e: 'infoRow', row: TableDataItem, index?: number): void;
  (e: 'TSelected', row: TableDataItem): void;
  (e: 'handleCurrentChange', row: TableDataItem): void;
  (
      e:
          | 'a'
          | 'b'
          | 'c'
          | 'd'
          | 'e'
          | 'f'
          | 'i'
          | 'j'
          | 'k'
          | 'l'
          | 'm'
          | 'n'
          | 'o'
          | 'p'
          | 'q',
      ...args: any[]
  ): void;
}>();

// 选中行的反应式引用
const selectedRows = ref<TableDataItem[]>([]);

const userId = getLocalStorage(Z_USER_ID);

const allColumns = ref<TableColumn[]>(props.tableDataHeader.map((col) => {
  if (col.prop) {
    return col;
  } else {
    return false;
  }
}).filter((s) => {
  if (s) {
    return s;
  }
}));

const visibleColumns = ref<string[]>(allColumns.value.map((col) => col.prop));

// 计算当前显示的列
const visibleTableDataHeader = computed(() =>
    allColumns.value.filter((col) => visibleColumns.value.includes(col.prop))
);

const localShowSettings = ref(props.showSettings);

// 监听 props.showSettings 的变化，并更新本地状态
watch(() => props.showSettings, (newVal) => {
  if (newVal) {
    localShowSettings.value = newVal;
  }
});

// 监听本地状态的变化，并通知父组件
watch(localShowSettings, () => {
  emits('closeSetting');
});

const store = useTableColumnsStore();

// 从 Pinia 加载列设置
onMounted(() => {
  const userId = getLocalStorage(Z_USER_ID);
  if (props.tableId.length) {
    const savedColumns = store.getUserColumns(userId, props.tableId);
    if (savedColumns.length > 0) {
      visibleColumns.value = savedColumns;
    } else {
      visibleColumns.value = allColumns.value.map((col) => col.prop); // 默认显示所有列
    }
  }
});

// 保存列设置到 Pinia
const saveColumnSettings = () => {
  if (props.tableId.length > 0) {
    store.saveUserColumns(userId, props.tableId, visibleColumns.value);
    localShowSettings.value = false;
  } else {
    ElMessage.warning('表格无ID，无法保存');
  }
};

// 处理选中行变化的方法
const handleSelectionChange = (val: TableDataItem[]) => {
  selectedRows.value = val;
  emits('TSelected', selectedRows);
  console.log('Selected Rows:', val);
};

const handleCurrentChange = (val) => {
  emits("handleCurrentChange", val);
}

const rowClick = (row) => {
  emits('rowClick', row);
};

// 按钮点击事件处理方法
const btnClick = (
    method:
        | 'deleteRow'
        | 'editRow'
        | 'detailRow'
        | 'infoRow'
        | 'handleCurrentChange'
        | 'a'
        | 'b'
        | 'c'
        | 'd'
        | 'e'
        | 'f'
        | 'i'
        | 'j'
        | 'k'
        | 'l'
        | 'm'
        | 'n'
        | 'o'
        | 'p'
        | 'q',
    row: TableDataItem,
    index: number,
    methodType: string = ''
) => {
  emits(method, row, index, methodType);
};

// 使用 requestAnimationFrame 来处理 ResizeObserver 的回调
const resizeObserver = new ResizeObserver((entries) => {
  requestAnimationFrame(() => {
    entries.forEach((entry) => {
      // 处理尺寸变化
      // console.log(entry.contentRect.width);
      return false
    });
  });
});

// 观察表格容器的尺寸变化
onMounted(() => {
  const tableContainer = document.querySelector('.el-table__body-wrapper');
  if (tableContainer) {
    resizeObserver.observe(tableContainer);
  }
});

</script>
<style lang="scss" scoped>
@import "@/assets/var";

.upgradeTable {
  overflow: auto;
  font-size: $--table-size;
  color: $--table-color;
  background: $--table-bg;
  //box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);
  --el-table-row-hover-bg-color: #2a3b5b; // 设置 hover 时的背景色

  --el-table-border-color: #3a4454; // 边框颜色

  & ::v-deep(.el-table__row.upgradeRow) {
    background: $--table-tr-bg;
    &:hover{
      color: $--table-row-hover-color;
    }
    //&.el-table__row{
    //  :hover{
    //    background: red;
    //  }
    //}
  }

  & ::v-deep(.el-table__row.warning-row) {
    background: $--table-tr-bg;
    &:hover{
      color: $--table-row-hover-color;
    }
  }

  & ::v-deep(.el-table__row.success-row) {
    background: $--table-tr-success-row-bg;
    &:hover{
      color: $--table-row-hover-color;
    }
  }

  & ::v-deep(thead.is-group th.el-table__cell){
    background: $--table-th-bg;
  }

  ::v-deep(.el-table__header-wrapper th) {
    /* 自定义表头样式 */
    & tr {
      background: $--table-th-bg;
    }

    background: $--table-th-bg;
    color: $--table-th-color;
    font-size: 14px;
  }
}

.el-tooltip__popper {
  font-size: 14px;
  max-width: 50%
}


.empty-total {
  height: 100%;
  width: 100%;
}

.custom-empty {
  margin-top: 70px;
  padding: 30px;
  //background-image: url("../../../assets/images/nodata/nodata.svg");
  background-size: 100% 100%;
  text-align: center;
}

.custom-empty i {
  font-size: 24px;
  margin-bottom: 10px;
  display: block;
}

.empty-text {
  font-family: "Microsoft YaHei";
  font-size: 14px;
  color: #59626d;
  margin-left: 5px;
}
</style>
